<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018\9\27 0027
 * Time: 13:45
 */

namespace app\Lib\Model\Systems;


use app\Lib\Exception\BlException;
use app\Lib\Exception\SysException;

class TopServer
{
    public $appkey;

    public $secretKey="56565656";

    public $format = "json";

    public $connectTimeout;

    public $readTimeout;

    public $method;

    public $sign;
    public $requestSignTime;
    public $requestTime;
    public $version;
    public $ip;

    /** 是否打开入参check**/
    public $checkRequest = true;

    protected $signMethod = "md5";

    public function __construct($appkey = "")
    {
        $this->appkey = $appkey;
    }

    public function setIp($ip){
        $this->ip = $ip;
    }

    protected function generateSign($params)
    {
        ksort($params);

        $stringToBeSigned = $this->secretKey;
        foreach ($params as $k => $v) {
            if(!is_array($v)){
                if ("@" != substr($v, 0, 1)) {
                    $stringToBeSigned .= "$k$v";
                }
            }else{
                if ("@" != substr(json_encode($v), 0, 1)) {
                    $stringToBeSigned .=$k.json_encode($v);
                }
            }
        }
        unset($k, $v);
        $stringToBeSigned .= $this->secretKey;
        //echo "<br/>".$stringToBeSigned;

        return strtoupper(md5($stringToBeSigned));
    }

    /**
     * @param $request
     * @throws SysException
     */
    public function execute($request)
    {
        //组装系统参数
        $sysParams["appkey"] = $this->appkey;
        $sysParams["format"] = $this->format;
        $sysParams["signMethod"] = $this->signMethod;
        $sysParams["method"] = $this->method;
        $sysParams["timestamp"] = urldecode($this->requestSignTime);
        $sysParams["version"] = $this->version;
//        $sysParams["ip"] = $this->ip;
//        throw new BlException(json_encode($sysParams));
        //获取业务参数
        $apiParams = $request;
        //签名
        $sysParams["sign"] = $this->generateSign(array_merge($apiParams, $sysParams));
        //echo $sysParams["sign"];
        if($this->sign!=$sysParams['sign']){
            throw new SysException("签名错误");
        }


    }

    /**
     * 验证参数
     * @throws SysException
     */
    public function checkTime(){
        if(!$this->requestSignTime)throw new SysException("参数错误");
        $time =strtotime(urldecode($this->requestSignTime));

        if(intval($this->requestTime)-intval($time)>1)throw new SysException("时间参数验证错误");
    }
    public function IpCheck($ip){

        return $ip;
    }
}